<template>
  <div class="search-page">
    <van-search
      class="search-box"
      v-model="searchText"
      show-action
      placeholder="请输入搜索关键词"
      background="#3296fa"
      @search="onSearch"
      @focus="showResults=false"
    >
      <span slot="action" @click="$router.back()">取消</span>
    </van-search>
    <search-results :searchText="searchText" v-if="showResults">
      <!-- 搜索结果 -->
    </search-results>
    <search-suggests v-else-if="searchText" :searchText="searchText" @to-search="onSearch($event)">
      <!-- 搜索建议 -->
    </search-suggests>
    <search-history v-else :searchHistorios="searchHistorios" @del-histories="delHistories($event)">
      <!-- 搜索历史 -->
    </search-history>
  </div>
</template>

<script>
import SearchSuggests from '@/components/searchItems/searchSuggests'
import SearchHistory from '@/components/searchItems/searchHistory'
import SearchResults from '@/components/searchItems/searchResults'
import { setItem, getItem } from '@/utils/storage'
export default {
  data() {
    return {
      // 通过输入框焦点判断是否显示搜索结果，通过输入框是否有字判断是否显示搜索建议
      searchText: '',
      showResults: false,
      searchHistorios: getItem('search-histories') || []
    }
  },
  components: {
    SearchSuggests,
    SearchHistory,
    SearchResults
  },
  methods: {
    onSearch(val) {
      // 回车搜索时,显示搜索结果组件
      if (!val) return
      this.showResults = true
      // 点击建议，输入框变成此项
      this.searchText = val
      if (!this.searchHistorios.includes(val)) {
        this.searchHistorios.unshift(val)
      }
    },
    delHistories(index) {
      console.log(index)
      // 删除历史搜索
      if (typeof index === 'number') {
        this.searchHistorios.splice(index, 1)
      } else {
        this.searchHistorios = []
      }
    }
  },
  watch: {
    searchHistorios(val) {
      // 监听历史记录变化，存储在本地
      setItem('search-histories', val)
    }
  }
}
</script>

<style lang='less' scoped>
.search-page {
  padding-top: 106px;
  .search-box {
    position: fixed;
    left: 0;
    top: 0;
    z-index: 2;
    width: 100%;
  }
  .van-search__action {
    color: #fff;
  }
}
</style>
